use rusqlite::{Connection, Result};

pub fn init(conn: &Connection) -> Result<()> {
    // 创建日历
    conn.execute(
        "CREATE TABLE if not exists calendar (
          id integer DEFAULT 0 PRIMARY KEY AUTOINCREMENT,
          flag integer,
          level integer,
          title text(30) NOT NULL,
          date text(10,2),
          start_time text(8),
          end_time text(8),
          content text DEFAULT '{}'
        )",
        (),
    )?;
    // 创建索引
    conn.execute(
        "CREATE INDEX if not exists idx_date ON calendar (
          date COLLATE BINARY DESC
        )",
        (),
    )?;



    Ok(())
}

/**
 * 日历
 */
pub struct Calendar {
    pub id: i32,
    pub flag: i32,
    pub level: i32,
    pub title: String,
    pub date: String,
    pub start_time: Option<String>,
    pub end_time: Option<String>,
    pub content: String,
}

/**
 * 根据日期获取当天待办
 */
pub fn get_todos_by_date(conn: &Connection, date: &str) -> Vec<Calendar> {
    let mut stmt = match conn.prepare("select id, flag, level, title, date, start_time, end_time, content from calendar where date = ?") {
        Ok(stmt) => stmt,
        Err(e) => {
            return Vec::new();
        }
    };

    let iter = match stmt.query_map([date], |row| {
        Ok(Calendar {
            id: row.get(0)?,
            flag: row.get(1)?,
            level: row.get(2)?,
            title: row.get(3)?,
            date: row.get(4)?,
            start_time: row.get(5)?,
            end_time: row.get(6)?,
            content: row.get(7)?,
        })
    }) {
        Ok(iter) => iter,
        Err(e) => {
            return Vec::new();
        }
    };

    iter.filter_map(|c|{
        c.ok()
    }).collect()
}